package com.qupai.lib_base.exfun

import android.app.Activity
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import android.widget.ImageView
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ObjectUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.qupai.lib_base.app.BaseApplication
import com.qupai.lib_base.app.BaseApplication.Companion.isDebug
import com.qupai.lib_base.utils.GlideRoundTransform
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * 使用view.visible()
 */
fun View?.visible() {
    if (this?.visibility != View.VISIBLE) {
        this?.visibility = View.VISIBLE
    }
}

fun View?.invisible() {
    if (this?.visibility != View.INVISIBLE) {
        this?.visibility = View.INVISIBLE
    }
}

fun View?.gone() {
    if (this?.visibility != View.GONE) {
        this?.visibility = View.GONE
    }
}

/**
 * Id
 * by lazy 方法代替findViewById
 * 使用：private val tv:TextView by id(R.id.tvEx)
 * @param T View
 * @param id View id
 */
fun <T : View> Activity.id(id: Int) = lazy { findViewById<T>(id) }

/**
 * Log
 * 使用log("any")
 * @param msg
 * @param tag
 */
fun log(msg: String, tag: String = "wingLog") {
    if (!isDebug) return
    Log.d(tag, msg)
}

fun logText(msg: String) {
    LogUtils.i(msg)
}

fun ImageView.load(url: Any) {
    if (ObjectUtils.isEmpty(url)) {
        LogUtils.e("图片地址为空")
    } else {
        val requestOptions = RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.DATA)
        Glide.with(this).load(url).dontAnimate().placeholder(this.drawable).apply(requestOptions).into(this)
    }
}

fun ImageView.loadNocache(url: Any) {
    if (ObjectUtils.isEmpty(url)) {
        LogUtils.e("图片地址为空")
    } else {
        val requestOptions = RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE)
        Glide.with(this).load(url).dontAnimate().placeholder(this.drawable).apply(requestOptions).into(this)
    }
}

fun ImageView.loadRound(url: Any, round: Int) {
    if (ObjectUtils.isEmpty(url)) {
        LogUtils.e("图片地址为空")
    } else {
        val options: RequestOptions = RequestOptions().diskCacheStrategy(DiskCacheStrategy.DATA).transform(GlideRoundTransform(this.context, round))
        Glide.with(this).load(url).dontAnimate().placeholder(this.drawable).apply(options).into(this)
    }
}


fun ImageView.load(url: Any, diskCacheStrategy: DiskCacheStrategy = DiskCacheStrategy.DATA, round: Int = 0) {
    if (ObjectUtils.isEmpty(url)) {
        LogUtils.e("图片地址为空")
    } else {
        val options: RequestOptions = if (round > 0) {
            RequestOptions().diskCacheStrategy(diskCacheStrategy).transform(GlideRoundTransform(this.context, round))
        } else {
            RequestOptions().diskCacheStrategy(diskCacheStrategy)
        }
        Glide.with(this).load(url).dontAnimate().placeholder(this.drawable).apply(options).into(this)
    }
}


/**
 * 精确到2位小数
 */
fun Double?.decimal2():Double{
    if(this==null||this==0.0)return 0.0
    return BigDecimal.valueOf(this).setScale(2, RoundingMode.HALF_UP).toDouble()
}


fun View.click(sleepTime: Long = 1000,  click: (v: View) -> Unit) {
    this.setOnClickListener {
        isClickable = false
        click(it)
        postDelayed({
            isClickable = true
        }, sleepTime)
    }
}

var readCountBg = 0
fun String?.getPathBitmap(width:Int = 100,height:Int = 100): Bitmap {
    try {
        if(this.isNullOrEmpty()){
            LogUtils.e("图片路径不存在，返回100像素透明bitmap")
            return Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888)
        }
        if(!this.contains("http")){
            LogUtils.e("本地图片路径，直接get bitmap")
            return ImageUtils.getBitmap(this)
        }
        var path = Glide.with(BaseApplication.psaApp).asFile().load(this)
            .diskCacheStrategy(if(this.startsWith("http")) DiskCacheStrategy.DATA else DiskCacheStrategy.NONE)
            .submit().get().absolutePath
        return  ImageUtils.getBitmap(path)
    }catch (e:Exception){
        Thread.sleep(500)
        readCountBg++
        if(readCountBg>=5){
            readCountBg=0
            LogUtils.e("读取地址转bitmap失败，返回像素透明bitmap")
            return Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888)
        }
        LogUtils.e("读取地址转bitmap失败，尝试${readCountBg} 重新获取：path="+this,e)
        return getPathBitmap()
    }
}

fun Int?.getResBitmap(width:Int = 100,height:Int = 100): Bitmap {
    try {
        if(this==null || this==0){
            LogUtils.e("图片res不存在，返回像素透明bitmap")
            return Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888)
        }
        return ImageUtils.getBitmap(this)
    }catch (e:Exception){
        LogUtils.e("res获取bitmap异常，返回像素透明bitmap",e)
        return Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888)
    }
}
